package com.smile.ye.utils;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class JwtUtils {
    public static void main(String[] args) {
    }

    private static final int TOKEN_TIME_OUT =  60 * 60 * 1000 * 24;

//    @Value("${jwt.secret}")
    private static  String TOKEN_SECRET_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";

    public static String createToken(String username,String id){
        Map<String,Object> headerMap = new HashMap();
        headerMap.put("typ","JWT");
        headerMap.put("alg","HS256");
        Map<String,Object> userMap = new HashMap();
        userMap.put("username",username);
//        userMap.put("id",id);
        JwtBuilder jwtBuilder = Jwts.builder();
        String token  = jwtBuilder
                .setHeaderParams(headerMap)
                .setSubject("subject")
                .addClaims(userMap)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_TIME_OUT))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,TOKEN_SECRET_KEY)
                .compact();
        return token;
    }

    public static String verifyToken(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(TOKEN_SECRET_KEY).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Object username = claims.get("username");
//        Object id = claims.get("id");
//        HashMap<String, String> map = new HashMap<>();
//        map.put("username",username.toString());
//        map.put("id",id.toString());
        return username.toString();
    }

}
